<?php require_once '../yubiphpbase/appinclude.php';
require_once '../yubiphpbase/yubi_lib.php';

if (($usrid = getUsrIdFromSession()) <= 0) {
	echo TIMEDOUT;
	exit;
}
$_SESSION['tab'] = 1;

$act = getHttpVal('act', '');
$client = getHttpVal('client',$_SESSION['client']);
$otp = getHttpVal('otp','');
$sec = getHttpVal('sec','');
writeLog('act='.$act.' client='.$client.' otp='.$otp, true);

if (strlen($act) > 0) {
	if ($act == 'impkey') { // add 1 key
		$alert = '';
		$devId = substr($otp, 0, 12);
		writeLog('modhex> devId='.$devId, true);
	 	$devId = modhexToB64($devId);
		writeLog('b64> devId='.$devId, true);
		
		if ($client < 0) {
			$alert = 'Client ['.$client.'] does not exist';
		} else if ($otp == '' || strlen($otp) < 12 || strlen($devId) < 5) {
			$alert = 'Enter the Yubikey token ID or OTP';				
		} else if ($sec == '' || strlen($sec) < 12) {
			$alert = 'Enter the AES secret key of the Yubikey';	
		}
		
		if (strlen($alert) > 1) {
			$_SESSION['alert'] = $alert;
			header('Location: index.php');
			exit;	
		}
		
		$active = getHttpVal('active', 1);
		$notes = getHttpVal('notes', '');

		if (($keyid=addNewKey($devId, $active, $sec, $notes, $client)) > 0) {
			$_SESSION['alert'] = 'New Yubikey '.$keyid.' added successfully';
			  makePopupURL('edit_client.php?client='.$client,'Client-'.$client,500);
		} else {
			$_SESSION['alert'] = 'Failed to add Yubikey '.$devId;
		}
		$_SESSION['alert'] .= ' for '.
			makePopupURL('edit_client.php?client='.$client,'Client-'.$client,500);
	} else { // add many keys
		// TODO
	}
	
	header('Location: index.php');
	exit;
} // End of performing act


?>
 
<table border=0 width=100%>
<tr><td align=left nowrap>
 <font size=2><b>
 This section is only used when you host your own Yubikey Management Service, or when<br>
 you re-program a Yubikey with your own AES secret by using the personalization tool and <br>
 want to update Yubico's database so its OTP can be validated by Yubico's validation server.
 </b></font>
 <br><br>
 
 <table><tr><td valign=top><img src=images/arrow.jpg></td>
 <td nowrap valign=bottom>
 <a href=#DOWN onclick="javascript:showImpKey(0,<?php echo $client;?>);">
 <b><font color=#008080 size=2><b>Add a Yubikey >></b></font></a> 
 <p><div id=impkey> </div>
 </td></tr></table>
 
</td></tr>

<tr><td align=left nowrap>
 
 <table><tr><td valign=top><img src=images/arrow.jpg></td>
 <td nowrap valign=bottom>
 <a href=#DOWN onclick="javascript:showImpKey(1);">
 <font color=#008080 size=2><b>Import Data of Yubikeys >></b></font></a> 
 <p><div id=impkeys> </div>
 </td></tr></table>
 
</td></tr>

</table>

</body>
</html>
